package com.jerry.hm.datastructure.queue;

import java.util.Iterator;

/**
 * 环形数组实现-方式三
 *
 * @author Jerry
 * @since 2024/10/3 13:00
 */
public class ArrayQueue3<E> implements Queue<E>, Iterable<E> {

    private final E[] array;
    private int head = 0;
    private int tail = 0;

    public ArrayQueue3(int capacity) {
        array = (E[]) new Object[capacity];
    }

    /**
     * 向队尾插入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        array[(int) (Integer.toUnsignedLong(tail) % array.length)] = e;
        tail++;
        return true;
    }

    /**
     * 从队首移除元素
     *
     * @return
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        int pollIndex = (int) (Integer.toUnsignedLong(head) % array.length);
        E target = array[pollIndex];
        array[pollIndex] = null;
        head++;
        return target;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[(int) (Integer.toUnsignedLong(head) % array.length)];
    }

    /**
     * 队列是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 队列是否已满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return tail - head == array.length;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            private int cur = head;

            @Override
            public boolean hasNext() {
                return cur < tail;
            }

            @Override
            public E next() {
                E target = array[(int) (Integer.toUnsignedLong(cur) % array.length)];
                cur++;
                return target;
            }
        };
    }
}
